import router from './router'
import store from './store'
import dynamic from './router/dynamic'
const loginand404 = ['/login', '/404']

// 一级路由筛选
const onerouting = (router) => {
  const res = router.map(item => {
    return item.split(':')[0]
  })
  // 筛选重复项，转为真数组
  return Array.from(new Set(res))
}
// 二级路由筛选
const tworouting = router => {
  const res = router.map(item => {
    return `${item.split(':')[0]}:${item.split(':')[1]}`
  })
  // console.log(res)
  return Array.from(new Set(res))
}
// 服务端对比本地路由筛选对比
const filterrouting = (onepermissions, twopermissions, dynamic) => {
  // console.log(onepermissions, twopermissions, dynamic)
  if (onepermissions.includes('*')) {
    return dynamic
  }
  // console.log('123123', onepermissions.includes('*'))

  const firstRoutes = dynamic.filter(item => onepermissions.includes(item.permission))
  // console.log()
  const res = firstRoutes.map(item => {
    return {
      ...item,
      children: item.children.filter(chind => twopermissions.includes(chind.permission))
    }
  })
  return res
}
// this.$router.options.routes
router.beforeEach(async(to, from, next) => {
  // console.log(123)
  if (store.state.user.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
      const res = await store.dispatch('menu/getprofile')
      // console.log(res.data.permissions)
      const onepermissions = onerouting(res.data.permissions)
      // console.log(onepermissions)
      const twopermissions = tworouting(res.data.permissions)
      // console.log(twopermissions)
      // console.log(dynamic)
      const filterroutes = filterrouting(onepermissions, twopermissions, dynamic)
      console.log(filterroutes)
      // 动态路由添加到路由表中，进行路由跳转
      filterroutes.forEach(item => router.addRoute(item))
      // 动态路由存到vuex中，渲染页面
      store.commit('menu/setdynamiclist', filterroutes)
    }
  } else {
    if (loginand404.some(item => item === to.path)) {
      next()
    } else {
      next('/login')
    }
  }
  // console.log(loginand404.some(item => item === '/404'))

  next()
})
